package com.itlaobing.aop.concepts;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class CalculatableTest4 {

    public static void main(String[] args) throws Exception {

        //
        final Calculatable target = new Calculator();
        Class<?> tc = target.getClass();
        ClassLoader cl = tc.getClassLoader();
        Class<?>[] interfaces = tc.getInterfaces();
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object result = null;
                String methodName = method.getName();
                long begin = 0;
                long end = 0;
                if ("divide".equals(methodName)){
                    begin = System.nanoTime();
                }
                result = method.invoke(target,args);
                if ("divide".equals(methodName)){
                    end = System.nanoTime();
                    System.out.println("方法[" +methodName+"]执行用时["+(end-begin)+"ns.]");
                }
                return result;
            }
        };

        final Object proxy = Proxy.newProxyInstance(cl,interfaces,handler);

        String desc = proxy.toString();
        System.err.println(desc);

        if (proxy instanceof Calculatable){
            Calculatable c = (Calculatable) proxy;
            long result = c.divide(15,3);
            System.err.println(result);
        }
    }
}
